from rest_framework import serializers
from .models import Environment, HostType, HostGroup, Host, HostMonitorData


class EnvironmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Environment
        fields = '__all__'


class HostTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = HostType
        fields = '__all__'


class HostGroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = HostGroup
        fields = '__all__'


class HostSerializer(serializers.ModelSerializer):
    environment_name = serializers.CharField(source='environment.name', read_only=True)
    host_type_name = serializers.CharField(source='host_type.name', read_only=True)
    created_by_username = serializers.CharField(source='created_by.username', read_only=True)
    host_groups_data = HostGroupSerializer(source='host_groups', many=True, read_only=True)
    host_groups_names = serializers.SerializerMethodField()

    # 格式化显示字段
    memory_display = serializers.SerializerMethodField()
    disk_display = serializers.SerializerMethodField()

    class Meta:
        model = Host
        fields = '__all__'
        read_only_fields = ['created_by', 'created_at', 'updated_at', 'last_check_time']

    def get_host_groups_names(self, obj):
        """获取主机组名称列表"""
        return [group.name for group in obj.host_groups.all()]

    def get_memory_display(self, obj):
        """格式化内存显示"""
        if obj.memory_info:
            return obj.memory_info
        elif obj.memory_total:
            return f"{obj.memory_total}MB"
        return ""

    def get_disk_display(self, obj):
        """格式化磁盘显示"""
        if obj.disk_info:
            return obj.disk_info
        elif obj.disk_total:
            return f"{obj.disk_total}GB"
        return ""

    def create(self, validated_data):
        validated_data['created_by'] = self.context['request'].user
        return super().create(validated_data)


class HostCreateSerializer(serializers.ModelSerializer):
    host_group_ids = serializers.ListField(child=serializers.IntegerField(), required=False)
    public_ip = serializers.IPAddressField(required=False, allow_null=True, allow_blank=True)
    private_ip = serializers.IPAddressField(required=False, allow_null=True, allow_blank=True)

    class Meta:
        model = Host
        fields = ['hostname', 'ip_address', 'public_ip', 'private_ip', 'ssh_port', 'ssh_username',
                 'ssh_password', 'ssh_private_key', 'environment', 'host_type', 'description',
                 'host_group_ids', 'os_type', 'os_version', 'cpu_cores', 'cpu_architecture',
                 'memory_total', 'memory_info', 'disk_total', 'disk_info']
    
    def create(self, validated_data):
        host_group_ids = validated_data.pop('host_group_ids', [])
        validated_data['created_by'] = self.context['request'].user
        
        host = Host.objects.create(**validated_data)
        
        if host_group_ids:
            host.host_groups.set(host_group_ids)
            
        return host


class HostMonitorDataSerializer(serializers.ModelSerializer):
    hostname = serializers.CharField(source='host.hostname', read_only=True)
    
    class Meta:
        model = HostMonitorData
        fields = '__all__'


# DatabaseInstanceSerializer, SQLAuditLogSerializer 和 SQLAuditLogCreateSerializer 已移动到 sql_management 应用中
